<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="修改时间" style="width: 308px">
          <el-date-picker
            v-model="daterangeUpdateTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">转换关系表</span></el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['wms:transformrules:add']"
          >新增
          </el-button>
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['wms:transformrules:export']"
          >导出
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="transformrulesList" border class="mt20">
        <el-table-column label="规则" prop="ruleId" v-if="true"/>
        <el-table-column label="关联的规格" prop="skuId">
          <template #default="scope">
            <span>{{ getSkuName(scope.row.skuId).skuName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="目标产品" prop="targetSkuId">
          <template #default="scope">
            <span>{{ getSkuName(scope.row.targetSkuId).skuName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="转换比例" prop="conversionRatio">
          <template #default="scope">
            <span>{{ scope.row.conversionRatio }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="产出率" prop="yieldRate">
          <template #default="scope">
            <span>{{ scope.row.yieldRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:transformrules:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['wms:transformrules:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-row>

    </el-card>
    <!-- 添加或修改转换关系表对话框 -->
    <el-drawer :title="title" v-model="open" size="50%" append-to-body>
      <el-form ref="transformrulesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联规格" prop="skuId">
          <el-select v-model="form.skuId" placeholder="请选择关联的规格" clearable>
            <el-option
              v-for="dict in oldSkuList"
              :key="dict.value"
              :label="dict.skuName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标产品" prop="targetSkuId">
          <el-select v-model="form.targetSkuId" placeholder="请选择目标产品" clearable>
            <el-option
              v-for="dict in newSkuList"
              :key="dict.value"
              :label="dict.skuName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转换比例" prop="conversionRatio">
          <el-input v-model="form.conversionRatio" placeholder="请输入转换比例,在0~100之间"/>
        </el-form-item>
        <el-form-item label="产出率" prop="yieldRate">
          <el-input v-model="form.yieldRate" placeholder="请输入产出率，在0~100之间"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Transformrules">
import {
  addTransformrules,
  delTransformrules,
  getTransformrules,
  listTransformrules,
  updateTransformrules
} from "@/api/wms/transformrules";
import {listAll} from "@/api/wms/itemSku";

const {proxy} = getCurrentInstance();

const transformrulesList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const daterangeUpdateTime = ref([]);
//原材料sku列表
const oldSkuList = ref([]);
const newSkuList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    updateTime: undefined
  },
  rules: {
    skuId: [
      {required: true, message: "关联的规格不能为空", trigger: "change"}
    ],
    targetSkuId: [
      {required: true, message: "目标产品不能为空", trigger: "change"}
    ],
    conversionRatio: [
      {required: true, message: "转换比例不能为空", trigger: "blur"}
      //转换比率必须是0~100的数字
      , {pattern: /^([1-9]\d?|100)$/, message: '转换比率必须是0~100的数字'}
    ],
    yieldRate: [
      {pattern: /^([1-9]\d?|100)$/, message: '产出率必须是0~100的数字'}]
  }
});

const {queryParams, form, rules} = toRefs(data);


/**
 * 获取skuList
 */
function getSkuList() {
  listAll().then(res => {
    oldSkuList.value = res.data;
    newSkuList.value = res.data;
  })
}

getSkuList();

//通过id获取sku名称
function getSkuName(id) {
  return oldSkuList.value.find(item => item.id === id);
}

/** 查询转换关系表列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listTransformrules(queryParams.value).then(response => {
    transformrulesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    ruleId: null,
    skuId: null,
    targetSkuId: null,
    conversionRatio: null,
    yieldRate: null,
    createdBy: null,
    updatedBy: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("transformrulesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加转换关系表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _ruleId = row.ruleId || ids.value
  getTransformrules(_ruleId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改转换关系表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["transformrulesRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.ruleId != null) {
        updateTransformrules(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addTransformrules(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ruleIds = row.ruleId || ids.value;
  proxy.$modal.confirm('是否确认删除转换关系表编号为"' + _ruleIds + '"的数据项？').then(function () {
    loading.value = true;
    return delTransformrules(_ruleIds);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/transformrules/export', {
    ...queryParams.value
  }, `transformrules_${new Date().getTime()}.xlsx`)
}

getList();
</script>
